﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleServiceBus.Bus.Pipeline;

namespace SimpleServiceBus.Bus.MessageManagement.MessageValueProviders
{
    public class DynamicMessageValueProvider<TMessageType> : IMessageValueProvider
    {
        private readonly bool _requiresMessageContext;
        private readonly Delegate _action;

        public DynamicMessageValueProvider(Func<TMessageType,IMessageContext,string> valueProvider)
        {
            _requiresMessageContext = true;
            _action = valueProvider;
        }

        public DynamicMessageValueProvider(Func<TMessageType,string> valueProvider)
        {
            _requiresMessageContext = false;
            _action = valueProvider;
        }

        public string GetMessageValue(MessageEnvelope message, IMessageContext messageContext)
        {
            if (message == null || _action == null)
                return String.Empty;

            object[] args = _requiresMessageContext ? new[] {message.Body, messageContext} : new[] {message.Body};
            object val = _action.Method.Invoke(_action.Target, args);

            if (val != null)
                return val.ToString();
            return String.Empty;
        }
    }
}
